<template>
  <el-form
    ref="form"
    class="login_container"
    :model="login"
    status-icon
    :rules="rules"
    label-width="70px"
  >
    <!-- h3要放在里面:只能有一个根,且title也是表单的一部分 -->
    <h3 class="login_title">gua工具</h3>
    <!-- prop对应rules里的键 -->
    <el-form-item label="用户名" prop="userName">
      <el-input v-model="login.userName" autocomplete="off"></el-input>
    </el-form-item>

    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="login.password" autocomplete="off"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button @click="submit" type="primary" style="margin-left:30px;margin-top:10px">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { setToken } from "@/utils/CookieUtil";
import { login, getDesktopMenu } from "@/api/user/user";
export default {
  data() {
    return {
      // 登陆数据
      login: {
        userName: "admin",
        password: "123456",
      },
      // 校验规则
      rules: {
        userName: [
          { required: "true", message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: "true", message: "请输入用户名", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    submit() {
      // 表单的校验
      this.$refs.form.validate((valid) => {
        if (valid) {
          login(this.login)
            .then((userInfo) => {
              // 记录cookie
              setToken(userInfo.token);
              // 跳转到首页
              this.$router.push("/home");
              this.$store.commit("setUserInfo", userInfo);
              // 获取菜单
              getDesktopMenu().then((menus) => {
                console.log("getMenu", menus);
                // 设置菜单
                this.$store.commit("setMenu", menus);
                // 动态添加路由
                this.$store.commit("addMenu", this.$router);
                // 跳转到首页
                this.$router.push("/home");
              });
            })
            .catch((e) => {
              console.log(e);
              // 验证失败的弹窗
              this.$message.error("操作失败");
            });
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.login_container {
  width: 350px;
  border: 1px solid #eaeaea;

  // 居中
  margin: 180px auto;

  padding: 35px 35px 15px 35px;

  // 让padding在width里面
  box-sizing: border-box;

  border-radius: 15px;
  background-color: #fff;
  box-shadow: 0 0 25px #cac6c6;

  .login_title {
    color: #505458;
    // 左右居中
    text-align: center;
    margin-bottom: 40px;
  }

  .el-input {
    width: 198px;
  }
}
</style>